package com.victor.utils.sms;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

import sun.misc.BASE64Encoder;

/**
 * 短信商相关调用方法
 * 
 * @author zhangbin
 *
 */
@SuppressWarnings("restriction")
public class SmsUseful {

	public static String createSign(TreeMap<String, Object> tm) {
		StringBuffer buf = new StringBuffer();
		for (Map.Entry<String, Object> en : tm.entrySet()) {
			String name = en.getKey();
			String value = en.getValue().toString();
			if (value != null && value.length() > 0 && !"null".equals(value)) {
				buf.append(name).append('=').append(value).append('&');
			}
		}
		String _buf = buf.toString();
		return _buf.substring(0, _buf.length() - 1);
	}

	public static String getKeyedDigestGBK(String strSrc, String key) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(strSrc.getBytes("GBK"));
			String result = "";
			byte[] temp;
			temp = md5.digest(key.getBytes("UTF8"));
			for (int i = 0; i < temp.length; i++) {
				result += Integer.toHexString((0x000000ff & temp[i]) | 0xffffff00).substring(6);
			}
			return result.toUpperCase();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 文件转String
	 *
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static String readFileAsString(String fileName) throws Exception {
		FileInputStream fis = new FileInputStream(fileName);
		BufferedInputStream in = new BufferedInputStream(fis);
		byte buffer[] = new byte[256];
		StringBuffer picStr = new StringBuffer();
		BASE64Encoder base64 = new BASE64Encoder();
		while (in.read(buffer) >= 0) {
			picStr.append(base64.encode(buffer));// 进行64位编码
		}
		fis.close();
		fis = null;
		in.close();
		in = null;
		buffer = null;
		return picStr.toString();
	}

}
